package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threablocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2021/7/15 15:32
 **/
@Service
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDto dto) {
        // 1. 校验参数 (是否登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 查询行为实体
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"关联的行为实体不存在");
        }
        // 3. 根据操作类型判断是 保存不喜欢   取消不喜欢
        Short type = dto.getType();
        Query query = Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        if (type.intValue() == 0) {
            // 3.1 保存不喜欢，  检查是否已经保存
            ApUnlikesBehavior unlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);

            // 已保存  请勿重复操作
            if (unlikesBehavior!=null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"您已经点击过不喜欢，请勿重复点击");
            }
            // 未保存       保存不喜欢行为
            unlikesBehavior = new ApUnlikesBehavior();
            unlikesBehavior.setEntryId(behaviorEntry.getId());
            unlikesBehavior.setArticleId(dto.getArticleId());
            unlikesBehavior.setType((short)0);
            unlikesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(unlikesBehavior);
        }else{
            // 3.2 取消不喜欢    删除对应行为数据
            mongoTemplate.remove(query,ApUnlikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
